package com.sgb.member.view_model;

import android.text.TextUtils;
import android.util.Log;

import com.sgb.member.MemberConfig;
import com.sgb.member.di.repository.MemberRepertory;
import com.sgb.member.entity.ListMResponse;
import com.sgb.member.entity.MemberLeaseBean;
import com.sgb.member.ui.fragment.BusinessLeaseFragment;
import com.sgb.member.ui.fragment.BusinessLeaseFragment2;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BusinessLeaseModel2 extends BaseViewModel {

    private BusinessLeaseFragment2 fragment;
    private final MemberRepertory mRepertory;
    private final int maxPageSize = 20;
    private int current;
    private CommonPopEntity mAll;

    public BusinessLeaseModel2(BusinessLeaseFragment2 activity, MemberRepertory repertory) {
        this.fragment = activity;
        this.mRepertory = repertory;

        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
    }



    // 会员租赁
    public void getLeaseType() {
        // 1机械， 2 设备，3车辆，4 房产，5土地，6工厂，7农机
        showOrHideDialog(true);
        mRepertory.getApi().getRentCategory().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    data.getData().add(0, new CommonPopEntity("", "全部"));
                    fragment.setTabLayoutData(data.getData());
                } else {
                    fragment.setTabLayoutData(new ArrayList<>());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CommonPopEntity>>> call, Throwable t) {
                super.onFailure(call, t);
                fragment.setTabLayoutData(new ArrayList<>());
            }


            @Override
            public void onFinally() {

            }
        });

    }


    public void showOrHideDialog(boolean aBoolean) {
        if (aBoolean) {
            if (!DialogHelper.isShowing()&&fragment.getActivity()!=null) {
                DialogHelper.showProgressDialog(fragment.getActivity(), "数据获取中...");
            }
        } else {
            DialogHelper.dismissProgressDialog();
            fragment.closeRecyclerRefreshing();
        }
    }

    public void rentPersonList(boolean isLoadMore,String keyword,
                         String mNo1, String mNo2, String mNo3,
                         String mNo6, String mNo7) {
        int currentPage = isLoadMore ? current + 1 : 1;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("page", currentPage);
        map.put("limit", maxPageSize);
        map.put("pageSize", maxPageSize);
        map.put("pageNum", currentPage);
        map.put("title", keyword==null?"":keyword);
        if (TextUtils.isEmpty(mNo3)) {
            mNo3 = "1";
        }
        map.put("sortWay", mNo3); //排序方式 -1 倒序 发布时间最早  ； 1正序 发布时间最近
        map.put("type", mNo1); //类型 1机械，2 设备， 3 车辆， 4 房产，5土地，6工厂
        map.put("firstCategoryNo", mNo2);//二级分类
        map.put("provinceNo", mNo6);
        map.put("cityNo", mNo7);
        map.put("areacode", mRepertory.getAreaCode());
        mRepertory.getApi().getPersonalLeaseHomeList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberLeaseBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberLeaseBean>>> data) {
                if(data.getData()!=null&& data.getData() != null&&data.getData().getList().size()>0){
                    current = data.getData().getCurrent();
                    int total = data.getData().getPages();
                    fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
                }else {
                    fragment.refreshRecycler(new ArrayList<>(), isLoadMore, true);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberLeaseBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }


    // 获取类别下级所有树形数据
    public void getLeaseCategory(int type, String category, boolean isShowLeftDialog) {
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("type", category);
        /*mRepertory.getApi().getCategory(map).enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    if (data.getData().get(0).getTypeName().equals("不限")) {
                        data.getData().get(0).setTypeName("全部");
                    }
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, data.getData());
                    } else {
                        fragment.setChooseItemData(type, data.getData());
                    }
                }
            }
        });*/
    }

    // 发布时间排序
    public void getLeaseTimeSort(int type, boolean isShowLeftDialog) {
        List<CommonPopEntity> list = new ArrayList<>();
        list.add(new CommonPopEntity("", "全部"));
        list.add(new CommonPopEntity("1", "发布时间最近"));
        list.add(new CommonPopEntity("-1", "发布时间最早"));
        if (isShowLeftDialog) {
            fragment.showLeftDialog(type, list);
        } else {
            fragment.setChooseItemData(type, list);
        }
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel(int type) {
        showOrHideDialog(true);
        mRepertory.getApi().getAddressEntityCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                showOrHideDialog(false);
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    List<CommonPopEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> datum : data.getData()) {
                        entities.add(new CommonPopEntity(datum.getNo(), datum.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    fragment.setChooseItemData(type, entities);
                    fragment.setAddressData(data.getData());
                }
            }
        });
    }

    public void getAddressCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData, String no, int type, boolean isShowLeftDialog) {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> scrDatum : scrData) {
            if (scrDatum.getId().equals(no)) {
                List<AddressEntity<List<AddressEntity>>> children = scrDatum.getChildren();
                if (children != null && children.size() > 0) {
                    List<CommonPopEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity>> child : children) {
                        entities.add(new CommonPopEntity(child.getNo(), child.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, entities);
                    } else {
                        fragment.setChooseItemData(type, entities);
                    }
                }
            }
        }
    }

//    public void getH5Url(int pos, String id) {
//        String name = "";
//        if (pos == 1) {
//            name = "mechanicsDetail";//机械
//        } else if (pos == 2) {
//            name = "equipmentDetails";//设备
//        } else if (pos == 3) {
//            name = "vehicleDetails";//车辆
//        } else if (pos == 4) {
//            name = "propertyDetails";//房产
//        } else if (pos == 5) {
//            name = "landDetails";//土地
//        } else if (pos == 6) {
//            name = "factoryDetails";//工厂
//        } else if (pos == 7) {
//            name = "farmDetail";//农机
//        }
//        DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
//        mRepertory.getApi().getUrlSetting(name).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
//            @Override
//            public void onSuccess(BaseEntity<H5ReEntity> response) {
//                DialogHelper.dismissProgressDialog();
//                if (response.body() == null || response.body().getState() == null) {
//                    return;
//                }
//                String url = response.body().getData().getUrl() + "?id=" + id + "&iosFlag=2";
//                WebViewX5HostActivity.start(activity, url);
//
//                String url = data.getData().getUrl() + "?id=" + id + "&iosFlag=1";
//                MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url,id,"lease", pos+"");
//            }
//        });
//    }

    public void getH5Url(String type, String id) {
        String name = "";
        if ("1".equals(type)) {
            name = "mechanicsDetail";//机械
        } else if ("2".equals(type)) {
            name = "equipmentDetails";//设备
        } else if ("3".equals(type)) {
            name = "vehicleDetails";//车辆
        } else if ("4".equals(type)) {
            name = "propertyDetails";//房产
        } else if ("5".equals(type)) {
            name = "landDetails";//土地
        } else if ("6".equals(type)) {
            name = "factoryDetails";//工厂
        } else if ("7".equals(type)) {
            name = "farmDetail";//农机
        }
        if (TextUtils.isEmpty(name)) {
            return;
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        mRepertory.getApi().getUrlSetting(name).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id + "&iosFlag=2";
                    MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url);
//                    WebViewX5HostActivity.start(activity, url);
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getMemberLevelData(int type, boolean isShowLeftDialog) {
        mRepertory.getApi().getMemberLevelList().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, data.getData());
                    } else {
                        fragment.setChooseItemData(type, data.getData());
                    }
                }
            }
        });
    }

}
